'use strict';
const Controller = require('egg').Controller;
const utils = require('../utils/utils');
const jwt = require('jsonwebtoken');

class UserController extends Controller {

  async info() {
    const { ctx } = this;
    ctx.body = {
      code: 1,
      data: ctx.userInfo,
    };
  }

  async message_code() {
    const { ctx } = this;
    const { phone } = ctx.request.query;
    ctx.session.code = utils.randomCode(6);
    if (phone) {
      ctx.body = {
        code: 1,
        message: `已经发送验证[${ctx.session.code}]到用户${phone}手机`,
      };
    } else {
      ctx.throw(422, '请发送手机号');
    }
  }

  async login() {
    const { ctx } = this;
    const { phone, msg_code } = ctx.request.body;
    const rule = {
      phone: { type: 'string', required: true },
      msg_code: { type: 'string', required: true },
    };
    ctx.validate(rule, ctx.request.body);
    if (ctx.session.code === msg_code) {
      const user = await ctx.service.user.find_user(phone);
      if (user) {
        const token = jwt.sign({ ...user }, 'liuyu000');
        ctx.cookies.set('token', token, {
          maxAge: 1000 * 60 * 60 * 24,
          httpOnly: false,
        });
        ctx.body = {
          code: 1,
          message: '用户登录成功',
        };
      } else {
        ctx.throw(422, '手机号未注册');
      }
    } else {
      ctx.throw(422, '验证码不正确');
    }
  }
}

module.exports = UserController;
